<template>
  <div class="email">
    <a-button type="primary" @click="visible = true" v-if="type === 'fixed'"
      >{{ $t("breach.steps.step2.email.open") }}（{{ emailTotal }}）</a-button
    >
    <div class="corner" v-if="type === 'corner'" @click="visible = true">
      <img
        :src="
          require(cornerImg === 'letter'
            ? '../../../assets/svg/breach/letter.svg'
            : '../../../assets/svg/breach/letterSuccess.svg')
        "
        alt=""
      />
    </div>
    <a-drawer
      :title="$t('breach.steps.step2.email.open')"
      width="70%"
      :visible.sync="visible"
      wrapClassName="email-drawer"
      @close="visible = false"
    >
      <a-button
        type="primary"
        icon="plus"
        class="mb-[10px]"
        :disabled="disabled"
        @click="newVisible = true"
        >{{ $t("breach.steps.step2.email.add") }}</a-button
      >
      <a-table
        :columns="columns"
        :dataSource="emailList"
        :pagination="{ total: emailTotal }"
        @change="getEmailList"
      >
        <template slot="attachments" slot-scope="text, record">
          <a
            v-for="item in record.attachments"
            :href="item.link"
            :key="item.link"
            download=""
            >{{ item.fileName }}<br
          /></a>
        </template>
        <template slot="EmailResultsStatus" slot-scope="text, record">
          <span :class="record.EmailResultsStatus === 2 ? 'fail' : ''">
            {{
              $t(
                `breach.steps.step2.email.table.status.${
                  record.EmailResultsStatus === 1 ? "success" : "fail"
                }`
              )
            }}
          </span>
        </template>
        <template slot="operate" slot-scope="text, record">
          <a-button
            type="link"
            v-if="record.EmailResultsStatus === 2"
            :disabled="disabled"
            @click="resend(record)"
            >{{ $t("breach.steps.step2.email.table.buttons.again") }}</a-button
          >
        </template>
      </a-table>
    </a-drawer>
    <a-modal
      :title="$t('breach.steps.step2.email.add')"
      :visible="newVisible"
      :closable="false"
      :ok-text="$t('breach.steps.step2.email.modal.buttons.send')"
      :cancel-text="$t('user.email.required11')"
      :confirm-loading="confirmLoading"
      dialogClass="email-modal"
      @ok="createEmail"
      @cancel="modalCancel"
    >
      <a-form
        :form="form"
        :label-col="{ span: lang ? 6 : 9 }"
        :wrapper-col="{ span: lang ? 18 : 15 }"
      >
        <a-form-item :label="$t('breach.steps.step2.email.table.getter')">
          <a-select
            :placeholder="
              $t('breach.steps.step2.email.modal.getter.placeholder')
            "
            v-decorator="[
              'EmailResultsRecipients',
              {
                rules: [
                  {
                    required: true,
                    message:
                      'breach.steps.step2.email.modal.getter.placeholder',
                  },
                ],
              },
            ]"
            show-search
            mode="multiple"
            @search="(...rest) => getUsers(...rest, 'userList')"
          >
            <a-select-option
              v-for="item in userList"
              :value="item.value"
              :key="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :label="$t('breach.steps.step2.email.modal.copy')">
          <a-select
            :placeholder="$t('breach.steps.step2.email.modal.copy.placeholder')"
            v-decorator="[
              'EmailResultsCc',
              {
                rules: [
                  {
                    required: true,
                    message: 'breach.steps.step2.email.modal.copy.placeholder',
                  },
                ],
              },
            ]"
            show-search
            @search="(...rest) => getUsers(...rest, 'copyUserList')"
          >
            <a-select-option
              v-for="item in copyUserList"
              :value="item.value"
              :key="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :label="$t('breach.steps.step2.email.table.title')">
          <a-input
            v-decorator="[
              'EmailResultsTitle',
              {
                rules: [
                  {
                    required: true,
                    message: 'breach.steps.step1.content.form.tip',
                  },
                ],
              },
            ]"
            :placeholder="$t('breach.steps.step1.content.form.tip')"
          ></a-input>
        </a-form-item>
        <a-form-item
          :label="$t('breach.steps.step2.email.table.content')"
          required
        ></a-form-item>
        <wang-editor
          v-if="newEditorVisible"
          ref="wangEditor"
          :value="editorValue"
          :placeholder="$t('breach.steps.step1.content.form.tip')"
        />
        <div class="reverse-button">
          <a-button type="link" @click="modalVisible = true">
            <img src="../../../assets/svg/breach/selectModal.svg" alt="" />
            {{ $t("breach.steps.step2.email.add.selectmodal") }}
          </a-button>
        </div>
        <!-- <a-form-item :label="$t('breach.steps.step2.email.table.attachments')">
          <a-select
            mode="multiple"
            v-decorator="['attachments']"
            :placeholder="
              $t(
                'breach.steps.step2.email.add.selectmodal.attachments.placeholder'
              )
            "
            show-search
            @search="getAttachmentList"
          >
            <a-select-option v-for="item in attachmentList" :key="item.value">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item> -->
        <a-form-item
          v-if="actionList && actionList.length"
          :label="$t('breach.steps.step2.email.add.selectmodal.relateaction')"
        >
          <a-select
            mode="multiple"
            v-decorator="['relateAction']"
            :placeholder="
              $t(
                'breach.steps.step2.email.add.selectmodal.attachments.placeholder'
              )
            "
          >
            <a-select-option v-for="item in actionList" :key="item.value">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal
      :title="$t('breach.steps.step2.email.add.selectmodal.title')"
      :visible="modalVisible"
      dialogClass="email-select-modal"
      @ok="selectEmailModal"
      @cancel="selectModalCancel"
    >
      <a-form
        :form="modalForm"
        :label-col="{ span: lang ? 6 : 12 }"
        :wrapper-col="{ span: lang ? 18 : 12 }"
        labelAlign="left"
      >
        <a-form-item
          :label="$t('breach.steps.step2.email.add.selectmodal.title')"
        >
          <a-select
            v-decorator="['modal']"
            :placeholder="
              $t('breach.steps.step2.email.add.selectmodal.title.placeholder')
            "
            show-search
            @change="changeModal"
          >
            <a-select-option
              v-for="item in emailTemplateList"
              :key="item.value"
              >{{ item.label }}</a-select-option
            >
          </a-select>
        </a-form-item>
        {{ $t("system.emailmanage.table.operate.review") }}:
        <div class="review-div">
          <a-form-item :label="$t('breach.steps.step2.email.table.title')">
            <a-input v-decorator="['EmailTitle']" disabled></a-input>
          </a-form-item>
          {{ $t("breach.steps.step2.email.table.content") }}:
          <wang-editor
            v-if="editorRefresh"
            ref="selectWangEditor"
            :value="selectEditorValue"
            :placeholder="$t('breach.steps.step1.content.form.tip')"
            :disabled="true"
            class="mt-[4px]"
          />
        </div>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { getUserList } from "@/api/common/form";
import WangEditor from "@/components/Editor/WangEditor.vue";
import {
  getAttachmentsPost,
  getEmailListPost,
  getEmailTemplateDetail,
  getEmailTemplateDrop,
} from "@/api/dataBreach/form";
import { sendEmail } from "@/api/dataBreach/json";
export default {
  name: "email",
  components: { WangEditor },
  props: [
    "breachId",
    "type",
    "cornerImg",
    "disabled",
    "defaultUser",
    "actionList",
  ],
  data() {
    return {
      visible: false,
      emailList: [],
      columns: [
        {
          title: () => this.$t("breach.steps.step2.email.table.title"),
          dataIndex: "EmailResultsTitle",
          key: "EmailResultsTitle",
        },
        {
          title: () => this.$t("breach.steps.step2.email.table.getter"),
          key: "EmailResultsRecipientsStr",
          dataIndex: "EmailResultsRecipientsStr",
        },
        {
          title: () => this.$t("breach.steps.step2.email.table.copy"),
          key: "EmailResultsCcStr",
          dataIndex: "EmailResultsCcStr",
        },
        {
          title: () => this.$t("breach.steps.step2.email.table.addresser"),
          key: "EmailResultsSenderStr",
          dataIndex: "EmailResultsSenderStr",
        },
        {
          title: () => this.$t("breach.steps.step2.email.table.sendtime"),
          key: "EmailResultsCreatetime",
          dataIndex: "EmailResultsCreatetime",
        },
        /* {
          title: () => this.$t("breach.steps.step2.email.table.attachments"),
          key: "attachments",
          scopedSlots: { customRender: "attachments" },
        }, */
        {
          title: () => this.$t("breach.list.content.table.status"),
          key: "EmailResultsStatus",
          scopedSlots: { customRender: "EmailResultsStatus" },
        },
        {
          title: () => this.$t("di.menus"),
          key: "operate",
          scopedSlots: { customRender: "operate" },
        },
      ],
      statusList: [
        { label: "breach.steps.step2.email.table.status.success", value: 1 },
        { label: "breach.steps.step2.email.table.status.fail", value: 2 },
      ],
      newVisible: false,
      form: this.$form.createForm(this),
      userList: [],
      copyUserList: [],
      lang: localStorage.getItem("lang").includes("zh-CN"),
      editorValue: "",
      modalForm: this.$form.createForm(this),
      emailTemplateList: [],
      modalVisible: false,
      editorRefresh: true,
      selectEditorValue: "",
      newEditorVisible: true,
      attachmentList: [],
      emailTotal: 0,
      emailDetail: {},
      confirmLoading: false,
    };
  },
  mounted() {
    this.init();
    let that = this;
    window.addEventListener("setItemEvent", function (e) {
      if (e.key == "lang") {
        that.lang = e.value.includes("zh-CN");
      }
    });
  },
  watch: {
    defaultUser: {
      handler(newVal) {
        this.form.setFieldsValue({ getter: newVal });
      },
      immediate: true,
    },
    newVisible(newVal) {
      this.newEditorVisible = newVal;
    },
    modalVisible(newVal) {
      this.editorRefresh = newVal;
    },
    breachId: {
      handler() {
        this.init();
      },
      immediate: true,
    },
  },
  methods: {
    async init() {
      this.getEmailList();
      let { data } = await getEmailTemplateDrop();
      this.emailTemplateList = data;
      // this.getAttachmentList();
    },
    async getEmailList(pagination) {
      let { data } = await getEmailListPost({
        page: pagination?.current || 1,
        pageSize: pagination?.pageSize || 10,
        BreachId: this.breachId,
      });
      this.emailTotal = data.Total;
      this.emailList = data.Lists;
    },
    async resend(row) {
      await sendEmail(row);
      this.getEmailList();
    },
    async getUsers(value, key) {
      const { data } = await getUserList({ UserEmail: value, UserName: value });
      this[key] = data;
    },
    modalCancel() {
      this.form.resetFields();
      this.newVisible = false;
    },
    async changeModal(Id) {
      let { data } = await getEmailTemplateDetail({ Id });
      let email = data;
      this.emailDetail = data;
      this.modalForm.setFieldsValue({ EmailTitle: email.EmailTitle });
      this.editorRefresh = false;
      this.selectEditorValue = email.EmailContent;
      this.editorRefresh = true;
    },
    selectModalCancel() {
      this.modalForm.resetFields();
      this.modalVisible = false;
    },
    selectEmailModal() {
      if (this.modalForm.getFieldValue("modal")) {
        let email = this.emailDetail;
        this.form.setFieldsValue({ EmailResultsTitle: email.EmailTitle });
        this.newEditorVisible = false;
        this.editorValue = email.EmailContent;
        this.newEditorVisible = true;
      }
      this.selectModalCancel();
    },
    /* async getAttachmentList(key) {
      let res = await getAttachmentsPost({
        BreachId: this.breachId,
        InfoName: key,
      });
      this.attachmentList = res.data;
    }, */
    async createEmail() {
      this.form.validateFields(async (err, value) => {
        if (!err) {
          this.confirmLoading = true;
          let resVal = { ...value };
          resVal.EmailResultsRecipients =
            resVal.EmailResultsRecipients.join(",");
          let res = await sendEmail({
            BreachId: this.breachId,
            ...resVal,
            EmailResultsContent: this.$refs.wangEditor.getContent(),
          });
          if (res.code === 1) {
            this.confirmLoading = false;
            this.newVisible = false;
            this.getEmailList();
          }
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.email {
  & > .ant-btn {
    width: 46px;
    position: fixed;
    top: 100px;
    right: 24px;
    z-index: 999;
    white-space: normal;
    height: auto;
    padding: 20px 2px;
    border-radius: 0;
    border-top-left-radius: 20px;
    border-bottom-left-radius: 20px;
    :deep(span) {
      word-break: break-all;
      overflow-wrap: break-word;
      word-wrap: break-word;
    }
  }
  .corner {
    background-color: #5877a1;
    height: 150px;
    width: 150px;
    transform: rotate(45deg);
    position: relative;
    cursor: pointer;
    img {
      position: absolute;
      bottom: 26px;
      left: 50%;
      transform: rotate(-45deg) translateX(-50%);
    }
  }
}
</style>
<style lang="less">
.email-drawer {
  .fail {
    color: #e03225;
  }
}
.email-modal {
  .reverse-button {
    display: flex;
    flex-direction: row-reverse;
    margin-top: 4px;
    .ant-btn {
      display: flex;
      align-items: center;
      img {
        margin-right: 4px;
      }
    }
  }
}
.email-select-modal {
  .review-div {
    border: 1px solid #bbb;
    padding: 10px;
    margin-top: 4px;
    border-radius: 6px;
  }
}
</style>